package com.fooddiary.web;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.fooddiary.service.IModelService;
import com.fooddiary.service.IWeightService;
import com.fooddiary.util.AppException;
import com.fooddiary.web.form.WeightForm;

/**
 * Dispatch requests for weight CRUD functionality <br> 
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Controller
public class WeightController extends AbstractController{

	private final String WEIGHT_FORM_KEY = "weightForm";
	private final String EDITWEIGHT_URL = "/private/editweight";
	private final String REDIRECT_URL = "redirect:/private/model/main.action";
	
	private final String INIT_WEIGHT_ACTION = "/private/weight/initEditWeight.action";
	private final String SAVE_WEIGHT_ACTION = "/private/weight/saveWeight.action";
	
	@Autowired
	IModelService modelService;
	
	@Autowired
	IWeightService weightService;
	
	@RequestMapping(value=INIT_WEIGHT_ACTION, method=RequestMethod.GET)
	public ModelAndView initEditWeightForm(@RequestParam (value = "id", required = false) Integer id){
		WeightForm weightForm = new WeightForm();
		ModelAndView mv = null;
		try {
			weightForm = weightService.initWeightForm(modelService.getModel(), id);
			mv = new ModelAndView(EDITWEIGHT_URL);
		} catch ( AppException err ) {
			weightForm.getErrors().add( err.getMessage() );
		}finally{		
			mv.addObject( WEIGHT_FORM_KEY, weightForm );
		}
		return mv;
	}
	
	@RequestMapping(value=SAVE_WEIGHT_ACTION, method=RequestMethod.POST)
	public ModelAndView submitWeightForm(@ModelAttribute(WEIGHT_FORM_KEY) WeightForm form,
			BindingResult result, SessionStatus status){
		ModelAndView mv = null;
		try {
			WeightForm weightForm = weightService.saveWeightForm( modelService.getModel(), form );
			if(CollectionUtils.isEmpty( weightForm.getErrors() )){
				mv = new ModelAndView( REDIRECT_URL );
			}else{
				mv = new ModelAndView( EDITWEIGHT_URL );
				mv.addObject( WEIGHT_FORM_KEY, weightForm );
			}
		} catch ( Exception err ) {
			mv = new ModelAndView( ERROR_URL );
		}
		return mv;
	}
}
